/**
 * 
 */
package com.nari.heatshare.dao;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.nari.coreframe.dao.hibernate3.GenericDaoImpl;
import com.nari.heatshare.model.IShareAreaResult;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.platform.unitconversion.EnergyConsumptionUnitUtil;
import com.nari.rescontroller.dao.IResourceAccessControlDao;

/**
 * 
 * @author Xiaopeng
 * @date 2013-8-19
 */
public class ShareAreaResultDaoImpl extends GenericDaoImpl<IShareAreaResult, String> 
		implements IShareAreaResultDao {
	private IResourceAccessControlDao iResourceAccessControlDao;

	/**
	 * 分页查询分摊域分摊结果
	 * @param projectUID 所属项目(可选)
	 * @param communityUID 所属小区(可选)
	 * @param shareAreaUID 所属分摊域(可选)
	 * @param shareName 分摊名称(可选)
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-9-4
	 */
	@SuppressWarnings("unchecked")
	public ResultWithPageCond<IShareAreaResult> queryAreaResultPage(String projectUID, 
			String communityUID, String shareAreaUID, String shareName, 
			PageCond pageCond) throws Exception {
		Criteria listCriteria = this.getCurrentSession().createCriteria(IShareAreaResult.class);
		Criteria countCriteria = this.getCurrentSession().createCriteria(IShareAreaResult.class);
		//所属项目
		if (projectUID!=null && !"".equals(projectUID.trim())) {
			listCriteria.add(Restrictions.eq("projectID", projectUID.trim()));
			countCriteria.add(Restrictions.eq("projectID", projectUID.trim()));
		}
		//所属小区
		if (communityUID!=null && !"".equals(communityUID.trim())) {
			listCriteria.add(Restrictions.eq("communityID", communityUID.trim()));
			countCriteria.add(Restrictions.eq("communityID", communityUID.trim()));
		}
		//所属分摊域
		if (shareAreaUID!=null && !"".equals(shareAreaUID.trim())) {
			listCriteria.add(Restrictions.eq("shareAreaID", shareAreaUID.trim()));
			countCriteria.add(Restrictions.eq("shareAreaID", shareAreaUID.trim()));
		}
		//分摊名称
		if (shareName!=null && !"".equals(shareName.trim())) {
			listCriteria.add(Restrictions.ilike("shareName", shareName.trim().toLowerCase(), MatchMode.ANYWHERE));
			countCriteria.add(Restrictions.ilike("shareName", shareName.trim().toLowerCase(), MatchMode.ANYWHERE));
		}
		//权限资源匹配
		String authorityRes = iResourceAccessControlDao.queryAuthorityProjResSql();
		if(!"".equals(authorityRes)) {
			//这是一个直接与底层数据库耦合的查询，注意避免数模更改带来的系统问题
			listCriteria.add(Restrictions.sqlRestriction("{alias}.t_project_id in("+authorityRes+")"));
			countCriteria.add(Restrictions.sqlRestriction("{alias}.t_project_id in("+authorityRes+")"));
		}
		//统计结果集个数
		int total = ((Long)countCriteria.setProjection(Projections.rowCount()).list().get(0)).intValue();
		//结果集排序
		listCriteria.addOrder(Order.desc("startDate")).addOrder(Order.asc("shareName"));
		//结果集分页
		listCriteria.setFirstResult(pageCond.getStart()).setMaxResults(pageCond.getLimit());
		//构造返回类型
		pageCond.setTotal(total);
		ResultWithPageCond<IShareAreaResult> areaResultPage = new ResultWithPageCond<IShareAreaResult>();
		areaResultPage.setList(listCriteria.list());
		areaResultPage.setPageCond(pageCond);
		return areaResultPage;
	}
	
	/**
	 * 通过所属关系（所属项目、所属小区、所属分摊域）查询分摊域分摊结果列表
	 * @param projectUID 所属项目(可选)
	 * @param communityUID 所属小区(可选)
	 * @param shareAreaUID 所属分摊域(可选)
	 * @return 若所属关系（所属项目、所属小区、所属分摊域）均不存在，则返回空列表
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-9-4
	 */
	@SuppressWarnings("unchecked")
	public List<IShareAreaResult> queryAreaResultsByBelongs(String projectUID, 
			String communityUID, String shareAreaUID) throws Exception {
		if((projectUID!=null && !"".equals(projectUID.trim())) 
				|| (communityUID!=null && !"".equals(communityUID.trim()))
				|| (shareAreaUID!=null && !"".equals(shareAreaUID.trim()))) {
			Criteria listCriteria = this.getCurrentSession().createCriteria(IShareAreaResult.class);
			//所属项目
			if (projectUID!=null && !"".equals(projectUID.trim())) {
				listCriteria.add(Restrictions.eq("projectID", projectUID.trim()));
			}
			//所属小区
			if (communityUID!=null && !"".equals(communityUID.trim())) {
				listCriteria.add(Restrictions.eq("communityID", communityUID.trim()));
			}
			//所属分摊域
			if (shareAreaUID!=null && !"".equals(shareAreaUID.trim())) {
				listCriteria.add(Restrictions.eq("shareAreaID", shareAreaUID.trim()));
			}
			//权限资源匹配
			String authorityRes = iResourceAccessControlDao.queryAuthorityProjResSql();
			if(!"".equals(authorityRes)) {
				//这是一个直接与底层数据库耦合的查询，注意避免数模更改带来的系统问题
				listCriteria.add(Restrictions.sqlRestriction("{alias}.t_project_id in("+authorityRes+")"));
			}
			//结果集排序
			listCriteria.addOrder(Order.desc("startDate")).addOrder(Order.asc("shareName"));
			return listCriteria.list();
		}
		return new ArrayList<IShareAreaResult>();
	}
	
	/**
	 * 格式化计量收费热价，并以热量单位[元/MWh]返回计量热价
	 * @param measureChargePrice 计量收费热价
	 * @param measureUnit 计量收费单位
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-10-4
	 */
	public double formatMeasureChargePriceToMWh(double measureChargePrice, 
			Integer measureUnit) throws Exception {
		String energyUnit = null;
		if(measureUnit == 1) {
			energyUnit = EnergyConsumptionUnitUtil.energyUnit_MWh;
		}
		if(measureUnit == 2) {
			energyUnit = EnergyConsumptionUnitUtil.energyUnit_kWh;
		}
		if(measureUnit == 3) {
			energyUnit = EnergyConsumptionUnitUtil.energyUnit_GJ;
		}
		/* 根据能量换算比例计算计量热价
		 * 1)目标能量单位/MWh = 换算比例
		 * 2)计量热价 = 价钱总额/目标能量单位 = 价钱总额/(MWh * 换算比例)
		 * 3)价钱总额/MWh = 计量热价 * 换算比例
		 *  */
		BigDecimal proportion = new BigDecimal(1)
				.divide(new BigDecimal(EnergyConsumptionUnitUtil.energyConvert2MWh(1, energyUnit)), new MathContext(6, RoundingMode.HALF_UP));
		return proportion.multiply(new BigDecimal(measureChargePrice)).doubleValue();
	}
	
	/**
	 * 通过唯一标识列表查询分摊域分摊id-shareName映射信息
	 * @param idList 唯一标识列表，若为空列表，则返回空映射
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-10-6
	 */
	public Map<String, String> queryShareResultMapByIDList(List<String> idList) throws Exception {
		// 查询项目id-shareName列表
		List<Object> shareResultAttrs = null;
		if (idList != null && idList.size() > 0) {
			StringBuffer queryHQL = new StringBuffer("select distinct sar.id,sar.shareName ");
			queryHQL.append("from IShareAreaResult sar ");
			queryHQL.append("where sar.id in(");
			for (int index = 0; index < idList.size(); index++) {
				queryHQL.append("'");
				queryHQL.append(idList.get(index));
				queryHQL.append("'");
				if (index < idList.size() - 1) {
					queryHQL.append(",");
				}
			}
			queryHQL.append(")");
			shareResultAttrs = this.runQueryHSqlObject(queryHQL.toString());
		}
		// 格式化id-shareName映射关系
		Map<String, String> shareResultMap = new HashMap<String, String>();
		if (shareResultAttrs != null && shareResultAttrs.size() > 0) {
			for (Object attrs : shareResultAttrs) {
				Object[] attrArray = (Object[]) attrs;
				shareResultMap.put((String) attrArray[0], (String) attrArray[1]);
			}
		}
		return shareResultMap;
	}

	/**
	 * @return the iResourceAccessControlDao
	 */
	public IResourceAccessControlDao getiResourceAccessControlDao() {
		return iResourceAccessControlDao;
	}

	/**
	 * @param iResourceAccessControlDao the iResourceAccessControlDao to set
	 */
	public void setiResourceAccessControlDao(
			IResourceAccessControlDao iResourceAccessControlDao) {
		this.iResourceAccessControlDao = iResourceAccessControlDao;
	}
	
}
